<?php
namespace Admin\Model;

class GoodsModel extends CommonModel {
    
    protected $fields = array('id','goods_name','goods_sn','cate_id','market_price','shop_price','goods_img','goods_thumb','goods_body','is_hot','is_rec','is_new','addtime','is_del','is_sale');
	//自定义自动验证
    protected $_validate = array(
    	array('goods_name','require','商品名称必须填写',1),
    	array('cate_id','checkCategory','分类必须填写',1,'callback'),
    	array('market_price','currency','市场价格格式不对'),
    	array('shop_price','currency','本店价格格式不对'),
    );
    //对分类进行验证
    public function checkCategory($cate_id){
    	$cate_id = intval($cate_id);
		if($cate_id > 0){
			return true;
		}
		return false;
    }
	//使用TP的钩子函数
	public function _before_insert(&$data){
		//添加时间
		$data['addtime'] = time();
		//处理货号
		if(!$data['goods_sn']){
			//没有货号自动生成
			$data['goods_sn'] = 'XB'.uniqid();
		}else{
			//有提交货号
			$info = $this -> where('goods_sn='.$data['goods_sn']) -> find();
			if($info){
				$this -> error = '货号重复';
				return false;
			}
		}
		//实现图片上传
		$upload = new \Think\Upload();
		$info = $upload -> uploadOne($_FILES['goods_img']);
		if(!$info){
			$this -> error = $upload -> getError();
		}
		//上传时候的图片地址
		$goods_img = 'Uploads/'.$info['savepath'].$info['savename'];
		//实现缩略图的制作
		$img = new \Think\Image();
		//打开图片
		$img -> open($goods_img);
		//制作缩略图
		$goods_thumb = 'Uploads/'.$info['savepath'].'thumb_'.$info['savename'];
		$img -> thumb(450,450) -> save($goods_thumb);
		$data['goods_img'] = $goods_img;
		$data['goods_thumb'] = $goods_thumb;
	}
	//在add完成之后自动执行  
	public function _after_insert($data){
		$goods_id = $data['id'];
		//接受提交的扩展分类
		$ext_cate_id = I('post.ext_cate_id');
		//对提交的数据进行去重
		$ext_cate_id = array_unique($ext_cate_id);
		foreach($ext_cate_id as $key => $value){
			if($value !=0){
				$list[] = array('goods_id' => $goods_id,'cate_id' => $value);
			}
		}
		//批量写入数据
		M('GoodsCate') -> addAll($list);
	}
	//获取商品信息
	public function listData(){
		//定义每页显示的数据条数
		$pagesize = 3;
		//获取数据总数
		$where = 'is_del=1';
		$count = $this -> where($where) -> count();
		//计算出分页导航
		$page = new \Think\Page($count,$pagesize);
		$show = $page -> show();
		//获取当前的页码
		$p = intval(I('get.p'));
		//获取具体的数据
		$data = $this -> where($where) ->page($p,$pagesize) -> select();
		//返回数据时需要将数据及分页的导航数据都返回
		return array('pageStr' => $show,'data' => $data);
	}
}